package com.example.shiyan01

import android.app.Application
import android.content.Context
import android.content.res.Configuration
import java.util.Locale

class MyApplication : Application() {

    override fun onCreate() {
        super.onCreate()
        // 应用保存的语言设置
        applySavedLanguage()
    }

    override fun attachBaseContext(base: Context) {
        super.attachBaseContext(updateBaseContextLocale(base))
    }

    private fun updateBaseContextLocale(context: Context): Context {
        val sharedPreferences = context.getSharedPreferences("AppPreferences", Context.MODE_PRIVATE)
        val languageCode = sharedPreferences.getString("selected_language", "") ?: ""

        return if (languageCode.isNotEmpty()) {
            setLocale(context, languageCode)
        } else {
            context
        }
    }

    private fun setLocale(context: Context, languageCode: String): Context {
        val locale = when (languageCode) {
            "en" -> Locale.ENGLISH
            "zh" -> Locale.SIMPLIFIED_CHINESE
            "es" -> Locale("es")
            else -> Locale.getDefault()
        }

        Locale.setDefault(locale)

        val configuration = Configuration(context.resources.configuration)
        configuration.setLocale(locale)

        return context.createConfigurationContext(configuration)
    }

    private fun applySavedLanguage() {
        val sharedPreferences = getSharedPreferences("AppPreferences", Context.MODE_PRIVATE)
        val languageCode = sharedPreferences.getString("selected_language", "") ?: ""

        if (languageCode.isNotEmpty()) {
            val locale = when (languageCode) {
                "en" -> Locale.ENGLISH
                "zh" -> Locale.SIMPLIFIED_CHINESE
                "es" -> Locale("es")
                else -> Locale.getDefault()
            }
            Locale.setDefault(locale)
        }
    }
}